package be.rubengerits.bluetooth.tester.filepicker;

import java.io.File;

import be.rubengerits.bluetooth.tester.R;
import be.rubengerits.bluetooth.tester.R.id;
import be.rubengerits.bluetooth.tester.R.layout;
import be.rubengerits.bluetooth.tester.R.string;
import android.app.*;
import android.os.*;
import android.content.*;
import android.view.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.*;

public class FilePickerDialogFragment extends DialogFragment {

	public interface FilePickerDialogListener {
		public void onDialogPositiveClick(DialogFragment dialog, File file);

		public void onDialogNegativeClick(DialogFragment dialog);
	}

	private FilePickerDialogListener mListener;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Build the dialog and set up the button click handlers
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(R.string.file_chooser_title);
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						mListener.onDialogNegativeClick(FilePickerDialogFragment.this);
					}
				});

		final FilePickerAdapter filePickerAdapter = new FilePickerAdapter(getActivity());
		builder.setAdapter(filePickerAdapter, null);

		final AlertDialog dialog = builder.create();
		
		dialog.getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
						File item = (File) filePickerAdapter.getItem(position);//filePickerAdapter.getItem(parent);
						if (item.isDirectory()) {
							filePickerAdapter.updatePosition(item);
						} else {
							mListener.onDialogPositiveClick(FilePickerDialogFragment.this, item);
							dialog.dismiss();
						}
					}
				});
		
		return dialog;
	}

		
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		try {
			mListener = (FilePickerDialogListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement FilePickerDialogListener");
		}
	}


//	@Override
//	public void onItemClick(AdapterView<?> adapterView, View view,
//			int position, long id) {
//		File filePickerChoosen = filePickerChoosen(adapterView, position);
//		if (filePickerChoosen != null) {
//			FilePickerDialogFragment.this.onClick(this.getDialog(),
//					DialogInterface.BUTTON_POSITIVE);
//			this.dismiss();
//		}
//	}

}
